/*
 * Amkai Enterprise Solution (AES.) 
 * Copyright 2004 by Amkai(TM), Inc.
 * www.amkai.com
 * 
 * Project: webservice
 * Package: com.amkai.aes.webservice.binary.objecthandler.personnel
 * File: PersonnelJobHandler.java
 * Created: 2010.11.03. 11:09:03
 * Author: Keri Kornel (keri.kornel)
 * 
 */

/**
 * 
 */
package com.amkai.aes.webservice.binary.objecthandler.personnel;

import java.io.Serializable;

import com.amkai.aes.aescommon.service.binary.job.personnel.PersonnelJob;
import com.amkai.aes.aescommon.service.binary.job.personnel.PersonnelJobKind;
import com.amkai.aes.aescommon.service.result.personnel.PersonnelJobResult;
import com.amkai.aes.server.manager.personnel.PersonnelManager;
import com.amkai.aes.webservice.binary.JobObjectHandler;
import com.amkai.common.extensions.hibernate.config.SiteManager;
import com.amkai.common.extensions.hibernate.config.manager.SessionManager;

/**
 * @author KeriKornel
 *
 */
// KKORNEL: AES-14980 - Created to replace domain commiter
public class PersonnelJobHandler implements JobObjectHandler<PersonnelJob, Serializable, PersonnelJobResult> {

	@Override
	public PersonnelJobResult process(PersonnelJob job, Serializable object) throws Exception {
		PersonnelJobResult result = new PersonnelJobResult();
		if (job.getJobKind() != null) {
			boolean needManagerCreate = (job.getJobKind() != PersonnelJobKind.SAVE_PHYSSTAFF);
			SessionManager sm = (needManagerCreate ? SiteManager.Start() : null);
			PersonnelManager manager = (needManagerCreate ? new PersonnelManager(sm) : null);
			try {
				switch (job.getJobKind()) {
					case SAVE_PHYSSTAFF: {
						result.setDomain(PersonnelManager.commitDomain(job));
						break;
					}
					case SAVE_PHYSSTAFF_WITH_PRIVILEGED_PROCEDURES: {
						result.setDomain(PersonnelManager.commitDomain(job));
						sm.openTransaction();
						manager.savePrivilegedProceduresByDomain(result.getDomain(), job.getPriviligedProcedures());
						sm.commitTransaction();
						break;
					}
					case DOWNLOAD_PRIVILEGED_PROCEDURES_BY_PRIVILEGE: {
						manager.setPrivilegedroceduresByPrivilege(result, job.getModuleDepartment().getId(), job.getPrivilegeId());
						break;
					}
					case DOWNLOAD_PRIVILEGED_PROCEDURES_BY_PHYSTAFF: {
						manager.setPrivilegedroceduresByPhysStaff(result, job.getModuleDepartment().getId(), job.getPrivilegeId());
						break;
					}
					case UPLOAD_PRIVILEGED_PROCEDURES_ONLY_BY_PHYSSTAFF: {
						sm.openTransaction();
						result.setCountOfAddedPrivileges(manager.addPrivilegedProceduresByPhysStaff(job.getPhysStaffId(), job.getPriviligedProcedures()));
						sm.commitTransaction();
						break;
					}
				}
			} finally {
				// KKORNEL: AES-15425
				if (needManagerCreate && (sm != null)) {
					sm.closeSession();
				}
			}
		}
		return result;
	}


}
